<template>
  <div id="mapDom" class="map"></div>
</template>

<script>
import Map from 'ol/Map.js'
import View from 'ol/View.js'
import TileLayer from 'ol/layer/Tile.js'
import XYZ from 'ol/source/XYZ.js'
import { defaults as defaultControls } from 'ol/control'

export default {
  name: 'BaseMap',
  props: {
    // 定义外部参数
    viewConf: {
      type: Object,
      default: () => ({})
    },
    defLyrs: {
      type: Array,
      default: () => ['cva_c', 'vec_c']
    }
  },
  emits: ['created'], // 定义自定义事件
  mounted()
  {
    this.initMap()
  },
  methods: {
    initMap()
    {
      // 用传入的 view 配置覆盖默认配置
      const viewOpts = Object.assign({
        projection: 'EPSG:3857',
        center: [12749285.009531122, 3565786.110442458],
        zoom: 15
      }, this.viewConf)

      const layerOptions = [
        {
          key: 'img_c',
          title: '天地图影像',
          option: {
            projection: 'EPSG:4326',
            url: 'http://t{0-7}.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=85da45d6b59507d49db4e857f9be8c05'
          }
        },
        {
          key: 'vec_c',
          title: '天地图',
          option: {
            projection: 'EPSG:4326',
            url: 'http://t{0-7}.tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=85da45d6b59507d49db4e857f9be8c05'
          }
        },
        {
          key: 'cva_c',
          title: '天地图注记',
          option: {
            projection: 'EPSG:4326',
            url: 'http://t{0-7}.tianditu.gov.cn/cva_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=85da45d6b59507d49db4e857f9be8c05'
          }
        },
        {
          key: 'gaode',
          title: '高德瓦片底图',
          option: {
            projection: 'EPSG:3857',
            url: 'http://mapcdn.lshida.com/maps/vt?lyrs=m@292000000&hl=zh-CN&gl=cn&src=app&x={x}&y={y}&z={z}&s='
          }
        }
      ]

      // 创建地图实例
      const map = new Map({
        target: 'mapDom', // 设置地图的 DOM 容器
        view: new View(viewOpts), // 设置地图的视图配置
        layers: layerOptions
          .filter(item => this.defLyrs.includes(item.key))
          .map(item =>
          {
            return new TileLayer({
              properties: {
                name: item.key,
                title: item.title
              },
              source: new XYZ(item.option)
            })
          }),
        controls: defaultControls({
          zoom: false,
          rotate: false,
          attribution: false
        })
      })

      // 将地图实例挂载到全局对象
      window.map = map

      // 触发创建完毕的事件，传回地图实例对象
      this.$emit('created', map)
    }
  }
}
</script>

<style scoped>
.map {
  width: 100vw;
  height: 100vh;
}
</style>
